package com.wqj.kyee.gps.nav;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapCarInfo;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapRestrictionInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.PoiInputItemWidget;
import com.amap.api.navi.view.RouteOverLay;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.wqj.kyee.gps.CarInfoDialog;
import com.wqj.kyee.gps.OnCarInfoUpdatedListener;
import com.wqj.kyee.gps.R;
import com.wqj.kyee.gps.ui.SearchActivity;
import com.wqj.kyee.gps.util.BaseTransitionInActivity;
import com.wqj.kyee.gps.util.Constants;
import com.wqj.kyee.gps.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class RouteShowActivity extends AppCompatActivity implements AMapNaviListener, View.OnClickListener, CompoundButton.OnCheckedChangeListener, OnCarInfoUpdatedListener,
                                                                    AMap.OnCameraChangeListener {

    //private boolean congestion, cost, hightspeed, avoidhightspeed;
    /**
     * 导航对象(单例)
     */
    private AMapNavi mAMapNavi;
    private AMap mAmap;
    /**
     * 地图对象
     */
    private MapView mRouteMapView;
    private Marker mStartMarker;
    private Marker mEndMarker;
    private NaviLatLng endLatlng; //= new NaviLatLng(39.955846, 116.352765);
    private NaviLatLng startLatlng; // = new NaviLatLng(39.925041, 116.437901);
    private List<NaviLatLng> startList = new ArrayList<NaviLatLng>();
    /**
     * 途径点坐标集合
     */
    private List<NaviLatLng> wayList = new ArrayList<NaviLatLng>();
    /**
     * 终点坐标集合［建议就一个终点］
     */
    private List<NaviLatLng> endList = new ArrayList<NaviLatLng>();
    /**
     * 保存当前算好的路线
     */
    private SparseArray<RouteOverLay> routeOverlays = new SparseArray<RouteOverLay>();

    /**
     * 当前用户选中的路线，在下个页面进行导航
     */
    private int routeIndex = 0;
    /**
     * 路线的权值，重合路线情况下，权值高的路线会覆盖权值低的路线
     **/
    private int zindex = 1;
    /**
     * 路线计算成功标志位
     */
    private boolean calculateSuccess = false;
    private boolean chooseRouteSuccess = false;

    private Double currentLat = Double.NaN;
    private Double ccurrentLng = Double.NaN;
    private String  city = "";

    private TextView sPointView;
    private TextView ePointView;


    private LinearLayout mOptionOne;
    private LinearLayout mOptionTwo;
    private LinearLayout mOptionThree;

    private TextView mTvTimeOne;
    private TextView mTvDisOne;
    private TextView mTvLabelOne;

    private TextView mTvTimeTwo;
    private TextView mTvDisTwo;
    private TextView mTvLabelTwo;

    private TextView mTvTimeThree;
    private TextView mTvDisThree;
    private TextView mTvLabelThree;

    private TextView mTvLicensePlateNumber;

    private ViewAnimator mSwitcher;

    AppCompatCheckBox mCongestionCb;
    AppCompatCheckBox mCostCb;
    AppCompatCheckBox mHightSpeedCb;
    AppCompatCheckBox mAvoidHightSpeedCb;

    private Button mSettingOKBtn;
    private Button mStartNavi;

    private ImageButton mShowPreferenceIb;

    private CarInfoDialog mDialog;
    private Switch mRestrictSwitch;

    private ImageButton mZoomInIb;
    private ImageButton mZoomOutIb;

    private Handler mHandler;

    RelativeLayout mResultLalyout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_show);
        //getSupportActionBar().hide();

        mResultLalyout = (RelativeLayout) findViewById(R.id.id_rl_navi);

        mHandler = new Handler();

        mRouteMapView = (MapView) findViewById(R.id.mapView);
        mRouteMapView.onCreate(savedInstanceState);
        mAmap = mRouteMapView.getMap();
        mAmap.setTrafficEnabled(true);

        initMapUI(mAmap.getUiSettings());

        mZoomInIb = (ImageButton) findViewById(R.id.id_btn_zoom_in);
        mZoomOutIb = (ImageButton) findViewById(R.id.id_btn_zoom_out);
        mZoomInIb.setOnClickListener(this);
        mZoomOutIb.setOnClickListener(this);

        mStartNavi = (Button) findViewById(R.id.id_btn_startNavi);
        mStartNavi.setOnClickListener(this);

        mOptionOne = (LinearLayout) findViewById(R.id.id_ll_optionOne);
        mOptionTwo = (LinearLayout) findViewById(R.id.id_ll_optionTwo);
        mOptionThree = (LinearLayout) findViewById(R.id.id_ll_optionThree);
        mOptionOne.setOnClickListener(this);
        mOptionTwo.setOnClickListener(this);
        mOptionThree.setOnClickListener(this);

        sPointView = (TextView) findViewById(R.id.sPointView);
        ePointView = (TextView) findViewById(R.id.ePointView);
        sPointView.setOnClickListener(this);
        ePointView.setOnClickListener(this);

        mTvTimeOne = (TextView) findViewById(R.id.id_tv_time_optOne);
        mTvDisOne = (TextView) findViewById(R.id.id_tv_distance_optOne);
        mTvLabelOne = (TextView) findViewById(R.id.id_tv_label_optOne);

        mTvTimeTwo = (TextView) findViewById(R.id.id_tv_time_optTwo);
        mTvDisTwo = (TextView) findViewById(R.id.id_tv_distance_optTwo);
        mTvLabelTwo = (TextView) findViewById(R.id.id_tv_label_optTwo);

        mTvTimeThree = (TextView) findViewById(R.id.id_tv_time_optThree);
        mTvDisThree = (TextView) findViewById(R.id.id_tv_distance_optThree);
        mTvLabelThree = (TextView) findViewById(R.id.id_tv_label_optThree);

        mSwitcher = (ViewAnimator) findViewById(R.id.id_va_pageSwitcher);

        mCongestionCb = (AppCompatCheckBox) findViewById(R.id.id_cb_congestion);
        mCostCb = (AppCompatCheckBox) findViewById(R.id.id_cb_cost);
        mHightSpeedCb = (AppCompatCheckBox) findViewById(R.id.id_cb_hightspeed);
        mAvoidHightSpeedCb  = (AppCompatCheckBox) findViewById(R.id.id_cb_avoidhightspeed);

        mCongestionCb.setOnCheckedChangeListener(this);
        mCostCb.setOnCheckedChangeListener(this);
        mHightSpeedCb.setOnCheckedChangeListener(this);
        mAvoidHightSpeedCb.setOnCheckedChangeListener(this);

        mSettingOKBtn = (Button) findViewById(R.id.id_btn_settingsOK);
        mSettingOKBtn.setOnClickListener(this);

        mShowPreferenceIb = (ImageButton) findViewById(R.id.id_ib_showPreference);
        mShowPreferenceIb.setOnClickListener(this);

        mTvLicensePlateNumber = (TextView) findViewById(R.id.id_tv_licensePlateNumber);

        mDialog = new CarInfoDialog();
        mDialog.setCarInfoUpdatedListerner(this);

        mRestrictSwitch = (Switch) findViewById(R.id.id_switch_restriction);
        mRestrictSwitch.setOnCheckedChangeListener(this);

        LinearLayout carInfo = (LinearLayout) findViewById(R.id.id_layout_carInfo);
        carInfo.setOnClickListener(this);

        initView();

        mStartMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.start_point))));
        mEndMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.end_point))));

        mAMapNavi = AMapNavi.getInstance(getApplicationContext());
        mAMapNavi.addAMapNaviListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            currentLat = intent.getDoubleExtra(Constants.EXTRA_CURRENT_LAT, Double.NaN);
            ccurrentLng = intent.getDoubleExtra(Constants.EXTRA_CURRENT_LNG, Double.NaN);

            if ((!currentLat.isNaN()) && (!ccurrentLng.isNaN())) {
                startLatlng = new NaviLatLng(currentLat, ccurrentLng);
                mStartMarker.setPosition(new LatLng(currentLat, ccurrentLng));

                mAmap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLat, ccurrentLng), 10f));
            }

            city = intent.getStringExtra(Constants.EXTRA_CURRENT_CITY);

            Poi endPoi = intent.getParcelableExtra(Constants.EXTRA_POI);
            if (endPoi != null) {
                endLatlng = new NaviLatLng(endPoi.getCoordinate().latitude, endPoi.getCoordinate().longitude);
                mEndMarker.setPosition(new LatLng(endPoi.getCoordinate().latitude, endPoi.getCoordinate().longitude));
                ePointView.setText(endPoi.getName());
            }
        }
    }

    private void initMapUI(UiSettings settings) {
        settings.setZoomControlsEnabled(false);
    }

    private void initView() {
        SharedPreferences userSettings = getSharedPreferences(Constants.Navi_Preferences, MODE_PRIVATE);
        //SharedPreferences.Editor editor = userSettings.edit();

        String licensePlateNumber = userSettings.getString(Constants.SP_KEY_LicensePlateNumber, "");
        mTvLicensePlateNumber.setText(licensePlateNumber);

        Boolean isRestrict = userSettings.getBoolean(Constants.SP_KEY_IsRestrict, false);
        mRestrictSwitch.setChecked(isRestrict);

        Boolean congestion = userSettings.getBoolean(Constants.SP_KEY_Congestion, false);
        mCongestionCb.setChecked(congestion);

        Boolean cost = userSettings.getBoolean(Constants.SP_KEY_Cost, false);
        mCostCb.setChecked(cost);

        Boolean avoidhightspeed = userSettings.getBoolean(Constants.SP_KEY_AvoidHightSpeed, false);
        mAvoidHightSpeedCb.setChecked(avoidhightspeed);

        Boolean hightspeed = userSettings.getBoolean(Constants.SP_KEY_HightSpeed, false);
        mHightSpeedCb.setChecked(hightspeed);
    }

    private void calculateRoute() {
        mSwitcher.setDisplayedChild(1);
        clearRoute();
        int strategyFlag = 0;
        try {

            String carNumber = mTvLicensePlateNumber.getText().toString();
            if (!carNumber.isEmpty()) {
                AMapCarInfo carInfo = new AMapCarInfo();
                //设置车牌
                carInfo.setCarNumber(carNumber);
                //设置车牌是否参与限行算路
                carInfo.setRestriction(mRestrictSwitch.isChecked());
                mAMapNavi.setCarInfo(carInfo);
            }
            strategyFlag = mAMapNavi.strategyConvert(mCongestionCb.isChecked(), mAvoidHightSpeedCb.isChecked(), mCostCb.isChecked(), mHightSpeedCb.isChecked(), true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (strategyFlag >= 0) {
            startList.clear();
            endList.clear();

            startList.add(startLatlng);
            endList.add(endLatlng);

            mAMapNavi.calculateDriveRoute(startList, endList, wayList, strategyFlag);
            //ToastUtil.show(getApplicationContext(), "Strategy: " + strategyFlag);
        }
    }

    public void onBackClick(View view) {
        this.finishAfterTransition();
    }

    @SuppressLint("RestrictedApi")
    private void startActivityWithOptions(Intent intent, int requestCode) {
        ActivityOptions transitionActivity =
                ActivityOptions.makeSceneTransitionAnimation(this);
        startActivityForResult(intent, requestCode, transitionActivity.toBundle());
    }


    @Override
    protected void onResume() {
        super.onResume();
        mRouteMapView.onResume();

        if (endLatlng != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    calculateRoute();
                }
            }, 400);
        }
        //mAmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLat, ccurrentLng), 10f));
    }

    @Override
    protected void onPause() {
        super.onPause();
        mRouteMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mRouteMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onStop() {
        super.onStop();

        mResultLalyout.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        startList.clear();
        wayList.clear();
        endList.clear();

        mRouteMapView.onDestroy();

        mAMapNavi.removeAMapNaviListener(this);
        mAMapNavi.destroy();
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.id_layout_carInfo:
                mDialog.show(getFragmentManager(), "Car Info");
                break;

            case R.id.sPointView:
                intent = new Intent(this, SearchActivity.class);
                intent.putExtra(BaseTransitionInActivity.EXTRA_TRANSITION, BaseTransitionInActivity.TRANSITION_FADE_FAST);
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, city);
                intent.putExtra(Constants.EXTRA_HINT, "输入起点");
                intent.putExtra(Constants.EXTRA_POINTTYPE, PoiInputItemWidget.TYPE_START);
                startActivityWithOptions(intent, Constants.SEARCH_START_REQUEST_CODE);
                break;

            case R.id.ePointView:
                intent = new Intent(this, SearchActivity.class);
                intent.putExtra(BaseTransitionInActivity.EXTRA_TRANSITION, BaseTransitionInActivity.TRANSITION_FADE_FAST);
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, city);
                intent.putExtra(Constants.EXTRA_HINT, "输入终点");
                intent.putExtra(Constants.EXTRA_POINTTYPE, PoiInputItemWidget.TYPE_DEST);
                startActivityWithOptions(intent, Constants.SEARCH_END_REQUEST_CODE);
                break;

            case R.id.id_ll_optionOne:
                routeIndex = 0;
                changeRoute();
                break;

            case R.id.id_ll_optionTwo:
                routeIndex = 1;
                changeRoute();
                break;

            case R.id.id_ll_optionThree:
                routeIndex = 2;
                changeRoute();
                break;

            case R.id.id_btn_settingsOK:
                if (endLatlng != null) {
                    mSwitcher.setDisplayedChild(1);
                    calculateRoute();
                } else {
                    ToastUtil.show(this, getString(R.string.info_show_s_and_e_donne));
                }
                break;

            case R.id.id_ib_showPreference:
                mSwitcher.setDisplayedChild(0);
                break;

            case R.id.id_btn_startNavi:
                Intent gpsintent = new Intent(getApplicationContext(), RouteNaviActivity.class);
                //gpsintent.putExtra("gps", true);
                startActivity(gpsintent);
                break;

            case R.id.id_btn_zoom_in:
                mAmap.animateCamera(CameraUpdateFactory.zoomIn(), 500, null);
                break;

            case R.id.id_btn_zoom_out:
                mAmap.animateCamera(CameraUpdateFactory.zoomOut(), 500, null);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Constants.SEARCH_LOCATION_RESULT_CODE) {

            Poi poi = data.getParcelableExtra(Constants.EXTRA_POI);

            if (requestCode == Constants.SEARCH_START_REQUEST_CODE) {

                if (poi != null) {
                    sPointView.setText(poi.getName());
                    startLatlng = new NaviLatLng(poi.getCoordinate().latitude, poi.getCoordinate().longitude);
                    mStartMarker.setPosition(new LatLng(poi.getCoordinate().latitude, poi.getCoordinate().longitude));

                    if (endLatlng != null)
                        calculateRoute();
                }


            } else if (requestCode == Constants.SEARCH_END_REQUEST_CODE) {

                if (poi != null) {
                    ePointView.setText(poi.getName());
                    endLatlng = new NaviLatLng(poi.getCoordinate().latitude, poi.getCoordinate().longitude);
                    mEndMarker.setPosition(new LatLng(poi.getCoordinate().latitude, poi.getCoordinate().longitude));

                    if (startLatlng != null) {
                        calculateRoute();
                    }
                }
            }
        }
    }


    @Override
    public void onCalculateRouteFailure(int i) {
        calculateSuccess = false;
        ToastUtil.showerror(getApplicationContext(), i);
    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        routeOverlays.clear();
        routeIndex = 0;

        //RelativeLayout rl = (RelativeLayout) findViewById(R.id.id_rl_navi);
//        final ScaleAnimation animation = new ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f,
//                Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f);
//        animation.setDuration(500);
        mResultLalyout.setVisibility(View.VISIBLE);

        LinearLayout ll = (LinearLayout) findViewById(R.id.id_ll_selection);
        if (ints.length == 1) {
            //ll.setVisibility(View.GONE);
            mOptionTwo.setVisibility(View.GONE);
            mOptionThree.setVisibility(View.GONE);
        } else if (ints.length == 2)  {
            //ll.setVisibility(View.VISIBLE);
            mOptionThree.setVisibility(View.GONE);
        } else {
            mOptionOne.setVisibility(View.VISIBLE);
            mOptionTwo.setVisibility(View.VISIBLE);
            mOptionThree.setVisibility(View.VISIBLE);
        }


        HashMap<Integer, AMapNaviPath> paths = mAMapNavi.getNaviPaths();
        for (int i = 0; i < ints.length; i++) {
            AMapNaviPath path = paths.get(ints[i]);
            if (path != null) {
                drawRoutes(ints[i], path);

                double second = path.getAllTime();
                long min = Math.round( second / 60);

                int distance = path.getAllLength();
                String disLabel = "";
                if (distance > 1000) {

                    double km = (double)distance / 1000;
                    km = (double) Math.round(km * 10) / 10;
                    disLabel = km + "公里";

                } else {
                    disLabel = distance + "米";
                }

                String[] label = path.getLabels().split(",");

                if (i == 0) {
                    mTvLabelOne.setText(label[0]);
                    mTvTimeOne.setText(min + "分钟");
                    mTvDisOne.setText(disLabel);
                } else if (i == 1) {
                    mTvLabelTwo.setText(label[0]);
                    mTvTimeTwo.setText(min + "分钟");
                    mTvDisTwo.setText(disLabel);
                } else if(i == 2) {
                    mTvLabelThree.setText(label[0]);
                    mTvTimeThree.setText(min + "分钟");
                    mTvDisThree.setText(disLabel);
                }
            }
        }

        changeRoute(); //
    }




    private void drawRoutes(int routeId, AMapNaviPath path) {
        calculateSuccess = true;
        mAmap.moveCamera(CameraUpdateFactory.changeTilt(0));
        RouteOverLay routeOverLay = new RouteOverLay(mAmap, path, this);
        routeOverLay.setTrafficLine(true);
        routeOverLay.setStartPointBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.marker_blue));
        routeOverLay.setEndPointBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.marker_blue));
        routeOverLay.addToMap();
        routeOverlays.put(routeId, routeOverLay);
    }

    public void changeRoute() {
        if (!calculateSuccess) {
            Toast.makeText(this, "请先算路", Toast.LENGTH_SHORT).show();
            return;
        }
        /**
         * 计算出来的路径只有一条
         */
//        if (routeOverlays.size() == 1) {
//            chooseRouteSuccess = true;
//            //必须告诉AMapNavi 你最后选择的哪条路
//            mAMapNavi.selectRouteId(routeOverlays.keyAt(0));
//            Toast.makeText(this, "导航距离:" + (mAMapNavi.getNaviPath()).getAllLength() + "m" + "\n" + "导航时间:" + (mAMapNavi.getNaviPath()).getAllTime() + "s", Toast.LENGTH_SHORT).show();
//            return;
//        }

        if (routeIndex >= routeOverlays.size())
            routeIndex = 0;
        int routeID = routeOverlays.keyAt(routeIndex);
        //突出选择的那条路
        for (int i = 0; i < routeOverlays.size(); i++) {
            int key = routeOverlays.keyAt(i);
            routeOverlays.get(key).setTransparency(0.4f);
        }
        routeOverlays.get(routeID).setTransparency(1);
        routeOverlays.get(routeID).zoomToSpan();
        /**把用户选择的那条路的权值弄高，使路线高亮显示的同时，重合路段不会变的透明**/
        routeOverlays.get(routeID).setZindex(zindex++);

        //必须告诉AMapNavi 你最后选择的哪条路
        mAMapNavi.selectRouteId(routeID);
        //Toast.makeText(this, "路线标签:" + mAMapNavi.getNaviPath().getLabels(), Toast.LENGTH_SHORT).show();
        //routeIndex++;
        chooseRouteSuccess = true;

        /**选完路径后判断路线是否是限行路线**/
        AMapRestrictionInfo info = mAMapNavi.getNaviPath().getRestrictionInfo();
        if (!TextUtils.isEmpty(info.getRestrictionTitle())) {
            Toast.makeText(this, info.getRestrictionTitle(), Toast.LENGTH_SHORT).show();
        }

        highlightView();
    }

    private void highlightView() {
        LinearLayout parent = (LinearLayout) findViewById(R.id.id_ll_selection);

        int children = parent.getChildCount();

        for (int i = 0; i < children; i++) {

            LinearLayout child = (LinearLayout) parent.getChildAt(i);

            if (routeIndex == i) {
                child.setBackgroundColor(Color.LTGRAY);

                int count = child.getChildCount();

                for (int j = 0; j < count; j++) {
                    TextView tv = (TextView) child.getChildAt(j);
                    tv.setTextColor(Color.parseColor("#3399dd"));
                }

            } else {
                child.setBackgroundColor(Color.WHITE);

                int count = child.getChildCount();

                for (int j = 0; j < count; j++) {
                    TextView tv = (TextView) child.getChildAt(j);
                    tv.setTextColor(Color.parseColor("#797979"));
                }
            }
        }
    }


    /**
     * 清除当前地图上算好的路线
     */
    private void clearRoute() {
        for (int i = 0; i < routeOverlays.size(); i++) {
            RouteOverLay routeOverlay = routeOverlays.valueAt(i);
            routeOverlay.removeFromMap();
        }
        routeOverlays.clear();
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        int id = compoundButton.getId();
        switch (id) {
            case R.id.id_cb_congestion:

                save2Preferences(Constants.SP_KEY_Congestion, isChecked);
                break;
            case R.id.id_cb_cost:

                if (isChecked) {
                    if (mHightSpeedCb.isChecked()) {
                        mHightSpeedCb.setChecked(false);
                    }
                }

                save2Preferences(Constants.SP_KEY_Cost, isChecked);
                break;
            case R.id.id_cb_avoidhightspeed:

                if (isChecked) {
                    if (mHightSpeedCb.isChecked()) {
                        mHightSpeedCb.setChecked(false);
                    }
                }

                save2Preferences(Constants.SP_KEY_AvoidHightSpeed, isChecked);
                break;
            case R.id.id_cb_hightspeed:

                if (isChecked) {
                    mCostCb.setChecked(false);
                    mAvoidHightSpeedCb.setChecked(false);
                }

                save2Preferences(Constants.SP_KEY_HightSpeed, isChecked);
                break;
            case R.id.id_switch_restriction:
                if (isChecked) {
                    if (mTvLicensePlateNumber.getText().toString().isEmpty()) {
                        mDialog.show(getFragmentManager(), "CarNumber");
                    }
                }

                save2Preferences(Constants.SP_KEY_IsRestrict, isChecked);

                break;
            default:
                break;
        }
    }

    private void save2Preferences(String key, Boolean isChecked) {
        SharedPreferences userSettings = getSharedPreferences(Constants.Navi_Preferences, MODE_PRIVATE);

        SharedPreferences.Editor editor = userSettings.edit();
        editor.putBoolean(key, isChecked);
        editor.commit();
    }


    @Override
    public void carInfoUpdated(String info) {
        if (info.isEmpty()) {
            if (mTvLicensePlateNumber.getText().toString().isEmpty())
                mRestrictSwitch.setChecked(false);
        } else {
            SharedPreferences userSettings = getSharedPreferences(Constants.Navi_Preferences, MODE_PRIVATE);
            //SharedPreferences.Editor editor = userSettings.edit();

            SharedPreferences.Editor editor = userSettings.edit();
            editor.putString(Constants.SP_KEY_LicensePlateNumber, info);
            editor.commit();

            ToastUtil.show(getApplicationContext(), "保存车牌号成功");

            mTvLicensePlateNumber.setText(info);
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        float currentZoom = cameraPosition.zoom;

        if (currentZoom >= 19.0f) {
            mZoomInIb.setEnabled(false);
        } else {
            mZoomInIb.setEnabled(true);
        }

        if (currentZoom <= 3.0f) {
            mZoomOutIb.setEnabled(false);
        } else {
            mZoomOutIb.setEnabled(true);
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {

    }

    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {

    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onGetNavigationText(String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {

    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {

    }

    @Override
    public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {

    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {

    }

    @Override
    public void hideModeCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {

    }

    @Override
    public void hideLaneInfo() {

    }


    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }

    @Override
    public void onPlayRing(int i) {

    }

}
